package com.tsl.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsl.reggie.common.R;
import com.tsl.reggie.domain.po.Employee;
import com.tsl.reggie.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Locale;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author 唐书亮
 * @since 2024-01-11
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @PostMapping("login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        R<Employee> employeeR = employeeService.checkLogin(request, employee);

        return  employeeR;
    }
    @PostMapping("logout")
    public R<String> logout(HttpServletRequest request){
        //将缓存里Session清除
        request.getSession().removeAttribute("userId");

        return R.success("退出成功");
    }

    @PostMapping("")
    public R<String> addEmployee(HttpServletRequest request,@RequestBody Employee employee){
        //1.给新添加的员工的密码加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employeeService.save(employee);
        return R.success("新增员工成功");
    }
    @GetMapping("/page")
    public R<Page> page(String name,Integer pageSize,Integer page){
        Page<Employee> pages=new Page<>(page,pageSize);
        LambdaQueryWrapper <Employee> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Employee> like = queryWrapper.like(name != null, Employee::getName, name)
                .orderByAsc(Employee::getUpdateTime);
        Page<Employee> record = employeeService.page(pages, like);

        return R.success(record);
    }
     @PutMapping
    public R<String> updateEmployee(HttpServletRequest request,@RequestBody Employee employee){
        log.info("{}",employee);
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
        public R<Employee> getEmployee(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if (employee != null){
            return  R.success(employee);
        }
        return R.error("没有这个用户信息");
            }


}
